package com.hou.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Base {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms

    public static void main(String[] args) throws Exception {
        //重试策略：初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //通过工厂建立连接
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(CONNECT_ADDR) //连接地址
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)//重试策略
                .build();
        curatorFramework.start();//一定要开启连接
        //增  creatingParentsIfNeeded:同时创建父节点  withMode:指定节点类型（不加withMode默认为持久类型节点）
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .forPath("/super/son", "儿子".getBytes());//路径、数据内容
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .forPath("/father/son", "儿子".getBytes());//路径、数据内容
        //删
        curatorFramework.delete().deletingChildrenIfNeeded().forPath("/super");//递归删除子节点
        //改
        curatorFramework.setData().forPath("/father/son", "新儿子".getBytes());
        //查
        byte[] bytes = curatorFramework.getData().forPath("/father/son");
        System.out.println(bytes.toString());
        //查找子节点
        curatorFramework.getChildren().forPath("/father").forEach(x -> System.out.println(x));
        //判断节点是否存在
        Stat stat = curatorFramework.checkExists().forPath("/super");
        System.out.println(stat);//不存在,返回bull
        //使用inBackground 绑定回调函数
        ExecutorService pool = Executors.newCachedThreadPool();
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                .inBackground((cf, curatorEvent) -> {//BackgroundCallback实现类
                    System.out.println("状态码" + curatorEvent.getResultCode());//0表示成功
                    System.out.println("type:" + curatorEvent.getType());//CREATE
                }, pool).forPath("/320/yaozhen", "姚振".getBytes());
        //使用线程池做回调
        Thread.sleep(Integer.MAX_VALUE);//等待,方便查看打印输出
    }
}
